# DIRTY

class World_load_save (object):
    """Stuff that does load and save a world"""
    
    def __init__ (self, world):
        self.world = world
        
    # Load / Save Function block
    # msp realated objects from and to strings
    # currently WITHOUT any upport for humanoids
    def villageFromString (self, str):
        """
        Takes a village string and returns village object created from it
        "V" + str(vill.tPosTi) + str(vill.tSizeTi) + str(tc.tPosPi) + vill.name + "\n"
        """
        if str[0] != "V": return None
        cmd = self.parseString(str)
        v = cVillage (cmd[4], self.grid, self.zBuffer)
        v.tagVillageArea(cmd[1],cmd[2])
        v.setVillageCenterWell(self.resHelper)
        return v
    def homeFromString (self, vill, str):
        """
        Takes a home-string and a village and creates home and field in corresponding village 
        "H" + str (h.tPosPi) + str(h.getField().tPosPi) + "\n"
        """
        if str[0] != "H": return None
        cmd = self.parseString(str)
        home = vill.addHome(self.resHelper, cmd[1])
        if home: vill.addField(self.resHelper, home, cmd[2])
    def woodFromString (self, str):
        if str[0] != "W": return None
        cmd = self.parseString(str)
        for h in xrange(0, cmd[2][1]):
            for w in xrange(0,cmd[2][0]):
                t = self.grid.getTileAtTi ((cmd[1][0]+w, cmd[1][1]+h))
                self.grid.register (t, cmd[3])
        self.woods.append ((cmd[1],cmd[2]))
    def treeFromString (self, str):
        if str[0] != "T": return None
        cmd = self.parseString(str)    
        pos = self.grid.getTileAtPi(cmd[1])
        res = self.resHelper.loadBuildingTar (os.path.join("res","gfx","tree.tar.gz"),pos.rPosPi.topleft)
        img = res[0].convert()
        img.set_colorkey ((255,0,255))
        tree = cSprite (pos.rPosPi.topleft, img, res[1], self.zBuffer)
        self.grid.register (pos, "tree")
        self.grid.register (pos, tree)
        self.grid.register (tree, cmd[2])
        self.grid.register (tree, "tree")
    def parseString(self, str):
        "parses a string for easier loading into a list, makes tuples from tuple-strings and so on" 
        # string e.g.: 'V(10, 20)(200,200)Entenhausen'
        # becomes: ['V', (10, 20), (200, 200), 'Entenhausen']
        cmd = [c for c in str.replace("(",")").replace(" ", "").replace("\n","").split (")") if c != ""]
        for c in enumerate(cmd):
            if c[1].find (",") != -1:
                tmp = c[1].split (",")
                cmd[c[0]] = tuple([int(t) for t in tmp])
        return cmd
    def treesToString (self):
        "Save all trees on the map into a atring"
        # get all "wood" tagged stuff from registry
        s = ""
        for w in enumerate(self.woods):
            trees = [t for t in self.grid.getObjsForTag("wood"+str(w[0])) if isinstance(t, blockengine.cSprite)]            
            if trees != []:
                s = s + "W"+str(w[1][0])+str(w[1][1])+"wood"+str(w[0])+"\n"
                for t in trees:
                    s = s + "T" + str(t.tPosPi)+"wood"+str(w[0])+"\n"
        return s
    def villageToString(self, vill):
        """save village to string"""    
        # zuerst alle villagecentern lesen, damit werden die villages ermitteln
        # und abspeichern als string:
        # village: pos, size, centerpos, name
        # dann alle hauser und dazugehoerige felder
        townObj = [o for o in self.grid.getObjsForTag(vill) if not isinstance(o, blockengine.cTile)]
        tc = [o for o in townObj if isinstance (o, village.cVillageCenter)][0]
        s = "V" + str(vill.tPosTi) + str(vill.tSizeTi) + str(tc.tPosPi) + vill.name + "\n"
        homes = [o for o in townObj if isinstance (o, village.cHome)]
        for h in homes:
            s = s + "H" + str (h.tPosPi) + str(h.getField().tPosPi) + "\n"
        return s    
    def saveMap (self, filename):
        f = open (filename, "w")
        s = self.villageToString (self.village)
        s = s + self.treesToString ()
        f.write (s)
        f.close()
    def loadMap (self, filename):
        """load file and create map"""
        f = open(filename,"r")
        for line in f:
            if line[0] == "V": 
                self.village = self.villageFromString(line)
            if line[0] == "H":
                self.homeFromString(self.village, line)
            if line[0] == "W":
                self.woodFromString(line)
            if line[0] == "T":
                self.treeFromString(line)
        f.close()